import 'dart:io';

import 'package:cat_eye/bean/sq_lite_bean.dart';
import 'package:cat_eye/config/string_config.dart';
import 'package:cat_eye/util/util.dart';
import 'package:flutter/cupertino.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

/*
* @Package: sqflite
* @ClassName: sqLite_manager
* @Author: szj
* @CreateDate: 8/3/21 9:29 AM
*
* 参考文档:[https://juejin.cn/post/6891411303798308872#heading-13]
* TODO SQLite管理器
*/
class SQLiteManager {
  static SQLiteManager _manager;

  SQLiteManager._();

  static SQLiteManager getInstance() {
    if (_manager == null) {
      _manager = SQLiteManager._();
    }
    return _manager;
  }

  // 创建表
  Future _onCreate(Database db, int version) async {
    db.execute("CREATE TABLE IF NOT EXISTS ${StringConfig.SQ_LITE_TABLE_NAME}("
        "id INTEGER PRIMARY KEY autoincrement, "
        "type TEXT, "
        "bodyImageUrl TEXT, "
        "authorImageUrl TEXT, "
        "time TEXT, "
        "videoTime TEXT, "
        "videoUrl TEXT, "
        "background TEXT, "
        "title Text);");
    return;
  }

  static Database _db;

  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await _initDB();
    return _db;
  }

  Future<Database> _initDB() async {
    // 路径获取是通过 path_provider 库，需要自行添加依赖
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, StringConfig.SQ_LITE_NAME);
    return await openDatabase(path, onCreate: _onCreate, version: 1);
  }

  /*
   * 添加用户数据
   */
  Future<void> insert(SqLiteBean sqLiteBean, BuildContext context) async {
    var _db = await db;

    //判断表中是否有该元素
    lookUp(sqLiteBean.bodyImageUrl).then((value) => {
          if (value)
            {
              //已经成功关注提醒
              snackBar(context, StringConfig.ALREADY_SUCCESS_FOLLOW)
            }
          else
            {
              //添加到表中
              _db.insert(StringConfig.SQ_LITE_TABLE_NAME, sqLiteBean.toMap(),
                  conflictAlgorithm: ConflictAlgorithm.fail),
              //关注成功提醒
              snackBar(context, StringConfig.FOLLOW_SUCCESS)
            }
        });
  }

  /*
    *  查询所有的数据
    */
  Future<List<SqLiteBean>> queryAllData() async {
    var _db = await db;
    List<Map<String, dynamic>> result =
        await _db.query(StringConfig.SQ_LITE_TABLE_NAME);
    if (result.length == null) return List<SqLiteBean>();
    return List.generate(result.length, (i) => SqLiteBean.fromJson(result[i]));
  }

  /*
    *  查询所有的数据[true存在 false不存在]
    */
  Future<bool> lookUp(String bodyImageUrl) async {
    var _db = await db;
    List<Map<String, dynamic>> result =
        await _db.query(StringConfig.SQ_LITE_TABLE_NAME);
    if (result.length == null) {
      return false;
    } else {
      var list =
          List.generate(result.length, (i) => SqLiteBean.fromJson(result[i]));

      var isExistence = false;

      //循环表中的所有数据
      list.forEach((element) {
        if (element.bodyImageUrl == bodyImageUrl) {
          //如果bodyImageUrl存在,则不能添加
          isExistence = true;
        }
      });

      return isExistence;
    }
  }

  /*
    *  根据bodyImageUrl删除表中元素
    */
  Future<void> delete(String bodyImageUrl) async {
    var _db = await db;
    // await _db.execute('ALTER TABLE ${StringConfig.SQ_LITE_TABLE_NAME} ALTER COLUMN $id TEXT');
    await _db.delete(StringConfig.SQ_LITE_TABLE_NAME,
        where: "bodyImageUrl = ?", whereArgs: [bodyImageUrl]);
  }
}
